/*
    IceCode toolkit - Test Framework.
    Copyright (C) 2011 Alfredo 'IceCoder' Mungo

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "libxml++/libxml++.h"
#include "XMLOutput.hpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>

namespace icecode {
  namespace test {

    void internal_XMLOutput_Test(icecode::test::Test& t, xmlpp::Element* tst)
    {
      tst->add_child_comment("XML Test result generated by IceCode-Test C++ Unit Test Framework");
      xmlpp::Element* passed = tst->add_child("passed");
      xmlpp::Element* failed = tst->add_child("failed");

      for(std::vector<std::string>::iterator it = t.v_passed.begin(); it != t.v_passed.end(); it++)
	{
	  xmlpp::Element* ass = passed->add_child("assert");
	  ass->add_child_text(*it);
	}

      for(std::vector<std::string>::iterator it = t.v_failed.begin(); it != t.v_failed.end(); it++)
	{
	  xmlpp::Element* ass = failed->add_child("assert");
	  ass->add_child_text(*it);
	}
    }

    void internal_XMLOutput_TimedTest(icecode::test::TimedTest& t, xmlpp::Element* tst)
    {
      auto ival /*interval*/ = static_cast<long double>((t.ts_end.tv_nsec - t.ts_start.tv_nsec));
      std::stringstream s_ival;

      internal_XMLOutput_Test(reinterpret_cast<icecode::test::Test&>(t), tst);

      s_ival << ival;

      tst->set_attribute("time", s_ival.str());
      tst->set_attribute("time-unit", "nanosecond");
    }

    void XMLOutput_Test(std::string fname, icecode::test::Test& t)
    {
      xmlpp::Document xml;
      xmlpp::Element* root = xml.create_root_node("test");
      internal_XMLOutput_Test(t, root);
      xml.write_to_file_formatted(fname);
    }

    void XMLOutput_TimedTest(std::string fname, icecode::test::TimedTest& t)
    {
      xmlpp::Document xml;
      xmlpp::Element* root = xml.create_root_node("test");
      internal_XMLOutput_TimedTest(t, root);
      xml.write_to_file_formatted(fname);
    }
  }
}
